<?php

namespace app\controller\api;

use app\BaseController;
use app\model\User;
use GuzzleHttp\Client;
use think\Response;

class Login extends BaseController
{
    const appid = "wx2eb2e36c4aa4829e";
    const secret = "9e6e08b226408ffbc9b2786b47ee40e4";

//    const ser
    public function miniLogin()
    {
        $param = $this->request->post();
        //获取用户授权信息
        $data = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=' . self::appid . '&secret=' . self::secret . '&js_code=' . $param['code'] . '&grant_type=authorization_code');
        $data = json_decode($data, true);
        if (empty($data['openid'])) throw new \Exception("获取用户信息失败");
        //用户登陆
        return $this->success($this->app->make(User::class)->minLogin($data['openid']));
    }

    public function getPhoneNumber(): Response
    {
        //获取用户授权信息
        $response = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . self::appid . "&secret=" . self::secret);
        $response = json_decode($response, true)['access_token'] ?? '';
        if (empty($response)) throw new \Exception("获取用户信息失败");
        $client = new Client([
            'base_uri' => 'https://api.weixin.qq.com/',
            'timeout' => 2.0,
            'verify' => false,
            'headers' => [
                'Content-Type' => 'application/json'
            ]
        ]);
        $data = $client->request('POST', 'wxa/business/getuserphonenumber?access_token=' . $response, [
            'json' => [
                'code' => $this->request->param('code')
            ]
        ]);
        $items = $data->getBody()->getContents();
        if (empty($items)) throw new \Exception('获取手机号失败');
        $items = json_decode($items, true);
        if ($items['errcode'] != 0) throw new \Exception($items['errmsg'], $items['errcode']);
        //绑定手机号
        $user = $this->request->user;
        $user->mobile = $items['phone_info']['phoneNumber'];
        $user->save();
        return $this->success($user);
    }
}
